package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.dto.ItemDto;
import cn.chinaflame.pagodas.entity.PaAgent;
import cn.chinaflame.pagodas.entity.VwItemArea;
import cn.chinaflame.pagodas.entity.YwItem;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.PaAgentRepository;
import cn.chinaflame.pagodas.repository.VwItemAreaRepository;
import cn.chinaflame.pagodas.repository.YwItemRepository;
import cn.chinaflame.pagodas.req.ItemAddReq;
import cn.chinaflame.pagodas.utils.DateTimes;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * 项目service
 *
 * @author created by boming
 * @date 2018年1月5日 上午9:40:37
 */
@Service
public class YwItemService {


    private static final Logger log = LoggerFactory.getLogger(YwItemService.class);

    @Autowired
    private YwItemRepository ywItemRepository;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private PaAgentRepository ywAgentRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PaAgentService paAgentService;
    @Autowired
    private VwItemAreaRepository vwItemAreaRepository;

    /**
     * 查询项目列表
     *
     * @param pageIndex
     * @param pageSize
     * @param provinceCode
     * @param cityCode
     * @param areaCode
     * @param id
     * @return
     */
    public Result<?> query(ItemAddReq req) {
        log.info("查询项目列表【service】req:{}", req);

        List<VwItemArea> itemAreaList = vwItemAreaRepository.findAll(new Specification<VwItemArea>() {
            @Override
            public Predicate toPredicate(Root<VwItemArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = Lists.newArrayList();
                list.add(cb.equal(root.get("state").as(String.class), Sysconst.ENABLED_TRUE));
//				if(!Strings.isNullOrEmpty(req.getAgentId()))
//					list.add(cb.equal(root.get("agentId").as(String.class), req.getAgentId()));
                if (!Strings.isNullOrEmpty(req.getProvinceCode()))
                    list.add(cb.equal(root.get("provinceCode").as(String.class), req.getProvinceCode()));
                if (!Strings.isNullOrEmpty(req.getCityCode()))
                    list.add(cb.equal(root.get("cityCode").as(String.class), req.getCityCode()));
                if (!Strings.isNullOrEmpty(req.getId()))
                    list.add(cb.equal(root.get("projectId").as(String.class), req.getId()));
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        List<ItemDto> dtoList = Lists.newArrayList();
        for (VwItemArea area : itemAreaList) {
            ItemDto dto = new ItemDto();
            dto.setAgentId(area.getAgentId());
            dto.setCityCode(area.getCityCode());
            dto.setCityName(area.getCityName());
            dto.setProvinceCode(area.getProvinceCode());
            dto.setProvinceName(area.getProvinceName());
            dto.setId(area.getProjectId());
            dto.setName(area.getProjectName());
            dtoList.add(dto);
        }
        return Result.create(dtoList);
    }

    /**
     * 分页查询项目列表
     *
     * @param pageIndex
     * @param pageSize
     * @param provinceCode
     * @param cityCode
     * @param areaCode
     * @param id
     * @return
     */
    public Result<List<ItemDto>> queryByPage(ItemAddReq req) {
        log.info("分页查询项目列表【service】req:{}", req);
        String str = paAgentService.queryAryId(req.getAgentId());
        String sql = "SELECT yi.id AS id,"
                + "yi.name AS name,"
                + "yi.province_code AS provinceCode,"
                + "yi.province_name AS provinceName,"
                + "yi.city_code AS cityCode,"
                + "yi.city_name AS cityName,"
                + "yi.area_code AS areaCode,"
                + "yi.area_name AS areaName,"
                + "yi.description AS description,"
                + "yi.project_id AS projectId,"
                + "yi.agent_id AS agentId,"
                + "yi.agent_name AS agentName,"
                + " yi.commission AS commission,"
                + "yi.state AS state,"
                + "yi.createtime AS createtime,"
                + "yi.updatetime AS updatetime "
                + "FROM yw_item yi INNER JOIN pa_agent pa ON (yi.agent_id = pa.id) WHERE 1 = 1 and yi.state=0";
        StringBuilder sb = new StringBuilder();
        if (!Strings.isNullOrEmpty(req.getId())) {
            sb.append(" and yi.id = ").append(req.getId());
        }
        if (!Strings.isNullOrEmpty(req.getProvinceCode())) {
            sb.append(" and yi.province_code = ").append(req.getProvinceCode());
        }
        if (!Strings.isNullOrEmpty(req.getCityCode())) {
            sb.append(" and yi.city_code = ").append(req.getCityCode());
        }
		/*if(!Strings.isNullOrEmpty(req.getAgentId())) {
			sb.append(" and yi.agent_id = ").append(req.getAgentId());
		}*/
        sb.append(" and yi.agent_id in (" + str + ")");
        sb.append(" ORDER BY yi.createtime DESC");
        JdbcPage<ItemDto> page = new JdbcPage<>(sql + sb.toString(), req.getPageSize(), req.getPageIndex(), jdbcTemplate, ItemDto.class);
        return Result.createPage(page.getPage(), req.getPageSize(), req.getPageIndex(), page.getCount());
    }

    public ItemDto querybyId(String id) {
        log.info("查询单个项目信息id:{}", id);
        YwItem item = ywItemRepository.findOne(id);
        if (item != null && Sysconst.ENABLED_FALSE.equals(item.getState())) return null;
        ItemDto dto = new ItemDto();
        BeanUtils.copyProperties(item, dto);
        return dto;
    }

    /**
     * 添加新项目
     *
     * @param req
     * @return
     */
    public ItemDto add(ItemAddReq req) {
        log.info("添加单个项目【service】req:{}", req);
        String id = idGeneratorService.generateItemId();
        req.setId(id);
        YwItem item = new YwItem();

        BeanUtils.copyProperties(req, item);
        item.setCreatetime(DateTimes.nowDateTime());
        item.setUpdatetime(DateTimes.nowDateTime());
        PaAgent ya = ywAgentRepository.findOne(item.getAgentId());
        item.setAgentName(ya.getName());
        item.setState(Sysconst.ENABLED_TRUE);
        item = ywItemRepository.saveAndFlush(item);
        ItemDto dto = new ItemDto();
        BeanUtils.copyProperties(item, dto);
        return dto;
    }

    /**
     * 更新项目
     *
     * @param req
     * @return
     */
    public ItemDto update(ItemAddReq req) {
        log.info("更新单个项目【service】req:{}", req);
        ParamPreconditions.checkNotEmpty(req.getId(), CodeEnum.FAIL.getCode(), "项目id不能为空");
        YwItem oldItem = ywItemRepository.findOne(req.getId());
        ParamPreconditions.checkArgument(oldItem != null, CodeEnum.FAIL.getCode(), "未找到该项目");
        YwItem item = new YwItem();
        BeanUtils.copyProperties(req, item);
        item.setCreatetime(oldItem.getCreatetime());
        item.setUpdatetime(DateTimes.nowDateTime());
        PaAgent ya = ywAgentRepository.findOne(item.getAgentId());
        item.setAgentName(ya.getName());
        item = ywItemRepository.saveAndFlush(item);
        ItemDto dto = new ItemDto();
        BeanUtils.copyProperties(item, dto);
        return dto;
    }

    /**
     * 删除项目
     *
     * @param id
     * @return
     */
    public boolean delete(String id) {
        log.info("删除单个项目【service】id:{}", id);
        ParamPreconditions.checkNotEmpty(id, CodeEnum.FAIL.getCode(), "id不能为空");
        ParamPreconditions.checkArgument(!id.equals("1043"), CodeEnum.FAIL.getCode(), "万佛塔项目不能删除");
        YwItem item = ywItemRepository.findOne(id);
        if (item == null) return true;
        item.setState(Sysconst.ENABLED_FALSE);
        ywItemRepository.saveAndFlush(item);
        return true;
    }

}
